import win32gui
import win32con
import pyautogui
import time

# 设置PyAutoGUI操作延迟
pyautogui.PAUSE = 0.5
pyautogui.FAILSAFE = True


def find_window_by_title(title_keyword):
    """根据窗口标题查找句柄"""
    result = [None]  # 使用列表来避免nonlocal声明问题

    def callback(hwnd, extra):
        if win32gui.IsWindowVisible(hwnd):
            window_title = win32gui.GetWindowText(hwnd)
            if title_keyword in window_title:
                result[0] = hwnd

    # 枚举所有顶级窗口
    win32gui.EnumWindows(callback, None)
    return result[0]


def set_window_foreground(hwnd):
    """将窗口激活到前台"""
    if hwnd:
        # 先显示窗口
        win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
        # 将窗口放到最前面
        win32gui.SetForegroundWindow(hwnd)
        time.sleep(1)
        return True
    return False


def send_key_to_window(hwnd, key):
    """向指定窗口发送按键"""
    if hwnd and set_window_foreground(hwnd):
        pyautogui.press(key)
        return True
    return False


def control_tdx_by_handle():
    """通过句柄控制已运行的通达信"""
    # 查找通达信窗口（标题包含"通达信"或"TdxW"）
    tdx_hwnd = find_window_by_title("通达信") or find_window_by_title("TdxW")

    if not tdx_hwnd:
        print("未找到通达信窗口，请先手动打开通达信")
        return

    print(f"找到通达信窗口，句柄: {tdx_hwnd}")

    # 激活窗口
    set_window_foreground(tdx_hwnd)

    # 执行一些操作示例
    print("执行操作: 打开上证指数")
    pyautogui.press('f6')  # 激活代码输入框
    time.sleep(0.5)
    pyautogui.typewrite("000001")
    pyautogui.press('enter')
    time.sleep(2)

    print("执行操作: 切换到K线图")
    pyautogui.press('f5')
    time.sleep(2)

    print("执行操作: 缩小K线")
    for _ in range(3):
        pyautogui.hotkey('ctrl', '-')
        time.sleep(0.5)


if __name__ == "__main__":
    control_tdx_by_handle()
